<template>
  <div class="text-to-image-panel">
    <!-- 面板标题 -->
    <div class="panel-header">
      <div class="header-content">
        <div class="header-icon">
          <div class="icon-bg">
            <PhImage :size="32" class="text-primary" />
          </div>
        </div>
        <div class="header-text">
          <h2 class="header-title">AI 文生图</h2>
          <p class="header-subtitle">通过文本描述生成高质量图片，释放你的创意想象</p>
          <div v-if="debugMode !== null" class="debug-status">
            <div class="debug-info">
              <span v-if="debugMode" class="debug-badge debug-mode">
                🔧 调试模式 - 使用模拟数据
              </span>
              <span v-else class="debug-badge production-mode"> 🚀 生产模式 - 使用真实API </span>
              <button
                class="debug-toggle-btn"
                @click="toggleDebugMode"
                :title="debugMode ? '切换到生产模式' : '切换到调试模式'"
              >
                <PhToggleLeft v-if="debugMode" :size="16" />
                <PhToggleRight v-else :size="16" />
                <span>切换</span>
              </button>
            </div>
          </div>
        </div>
      </div>
      <div class="header-decoration"></div>
    </div>

    <!-- 提示词输入 -->
    <div class="input-section">
      <div class="input-header">
        <div class="input-label">
          <PhPencil :size="18" class="text-primary" />
          <span class="label-text">描述你想要的图片</span>
        </div>
        <div class="char-counter">
          <span class="counter-text">{{ prompt.length }}</span>
          <span class="counter-divider">/</span>
          <span class="counter-max">1000</span>
        </div>
      </div>
      <div class="textarea-wrapper">
        <textarea
          v-model="prompt"
          class="prompt-textarea"
          placeholder="例如：一只可爱的橘猫在花园里玩耍，阳光明媚，高清摄影风格，4K超清画质"
          maxlength="1000"
        ></textarea>
        <div class="textarea-glow"></div>
      </div>

      <!-- 快捷模板按钮 -->
      <div class="template-actions">
        <button
          class="template-toggle-btn"
          @click="toggleTemplates"
          :class="{ active: showTemplates }"
        >
          <PhMagicWand :size="16" />
          <span>快捷模板</span>
          <div class="template-count">{{ promptTemplates.length }}</div>
        </button>
      </div>
    </div>

    <!-- 模板选择面板 -->
    <div v-if="showTemplates" class="templates-panel">
      <div class="templates-header">
        <div class="templates-title">
          <PhMagicWand :size="18" class="text-primary" />
          <span>选择提示词模板</span>
        </div>
        <button class="close-btn" @click="showTemplates = false">
          <PhX :size="16" />
        </button>
      </div>

      <!-- 搜索和分类 -->
      <div class="templates-filters">
        <div class="search-box">
          <PhMagnifyingGlass :size="16" class="search-icon" />
          <input
            v-model="searchKeyword"
            type="text"
            placeholder="搜索模板..."
            class="search-input"
          />
        </div>

        <div class="category-tabs">
          <button
            v-for="category in categories"
            :key="category"
            class="category-tab"
            :class="{ active: selectedCategory === category }"
            @click="selectedCategory = category"
          >
            {{ category }}
          </button>
        </div>
      </div>

      <!-- 模板列表 -->
      <div class="templates-grid">
        <div
          v-for="template in filteredTemplates"
          :key="template.id"
          class="template-card"
          @click="selectTemplate(template)"
        >
          <div class="template-header">
            <div class="template-name">{{ template.name }}</div>
            <div class="template-category">{{ template.category }}</div>
          </div>
          <div class="template-prompt">{{ template.prompt }}</div>
          <div class="template-tags">
            <span v-for="tag in template.tags" :key="tag" class="template-tag">
              <PhTag :size="12" />
              {{ tag }}
            </span>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredTemplates.length === 0" class="templates-empty">
        <PhMagicWand :size="48" class="empty-icon" />
        <div class="empty-title">未找到匹配的模板</div>
        <div class="empty-subtitle">尝试调整搜索关键词或选择其他分类</div>
      </div>
    </div>

    <!-- 参数设置 -->
    <div class="params-section">
      <div class="params-header">
        <PhGear :size="18" class="text-primary" />
        <span class="params-title">生成参数</span>
      </div>

      <div class="params-grid">
        <!-- 宽高比选择 -->
        <div class="param-group">
          <label class="param-label">
            <PhRectangle :size="16" class="text-primary" />
            <span>宽高比</span>
          </label>
          <div class="select-wrapper">
            <select v-model="aspectRatio" class="param-select">
              <option value="1:1">1:1 - 正方形</option>
              <option value="16:9">16:9 - 横向宽屏</option>
              <option value="9:16">9:16 - 竖向全屏</option>
              <option value="4:3">4:3 - 传统横向</option>
              <option value="3:4">3:4 - 传统竖向</option>
            </select>
            <PhCaretDown :size="14" class="select-icon" />
          </div>
        </div>

        <!-- 响应格式 -->
        <div class="param-group">
          <label class="param-label">
            <PhFileImage :size="16" class="text-primary" />
            <span>输出格式</span>
          </label>
          <div class="select-wrapper">
            <select v-model="responseFormat" class="param-select">
              <option value="url">URL 链接</option>
              <option value="base64">Base64 数据</option>
            </select>
            <PhCaretDown :size="14" class="select-icon" />
          </div>
        </div>
      </div>
    </div>

    <!-- 生成按钮 -->
    <div class="action-section">
      <button class="reset-btn" @click="resetForm">
        <PhArrowCounterClockwise :size="16" />
        <span>重置</span>
      </button>
      <button
        class="generate-btn"
        :class="{ generating: generating, disabled: !prompt.trim() || generating }"
        :disabled="!prompt.trim() || generating"
        @click="generateImage"
      >
        <div class="btn-content">
          <div class="btn-icon">
            <PhSparkle v-if="!generating" :size="18" />
            <div v-if="generating" class="loading-spinner"></div>
          </div>
          <span class="btn-text">{{ generating ? '正在生成...' : '开始生成' }}</span>
        </div>
        <div class="btn-glow"></div>
      </button>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-alert">
      <div class="error-icon">
        <PhWarning :size="20" />
      </div>
      <div class="error-content">
        <div class="error-title">生成失败</div>
        <div class="error-message">{{ error }}</div>
      </div>
    </div>

    <!-- 生成结果 -->
    <div v-if="generatedImages.length > 0" class="result-section">
      <div class="result-header">
        <div class="result-title">
          <PhImages :size="20" class="text-primary" />
          <span>生成结果</span>
        </div>
        <div class="result-count">{{ generatedImages.length }} 张图片</div>
      </div>

      <div class="images-grid">
        <div v-for="(image, index) in generatedImages" :key="index" class="image-card">
          <div class="image-container">
            <img :src="image.url" :alt="`生成的图片 ${index + 1}`" class="generated-image" />
            <div class="image-overlay">
              <div class="image-actions">
                <button
                  class="action-btn download-btn"
                  @click="downloadImage(image.url, index)"
                  title="下载图片"
                >
                  <PhDownload :size="16" />
                </button>
                <button
                  class="action-btn copy-btn"
                  @click="copyImageUrl(image.url)"
                  title="复制链接"
                >
                  <PhCopy :size="16" />
                </button>
              </div>
            </div>
            <div class="image-gradient"></div>
          </div>
          <div class="image-info">
            <div class="image-index">图片 #{{ index + 1 }}</div>
            <div v-if="result" class="image-cost">${{ (result.cost || 0).toFixed(4) }}</div>
          </div>
        </div>
      </div>

      <!-- 元数据 -->
      <div v-if="result" class="metadata-section">
        <div class="metadata-header">
          <PhInfo :size="18" class="text-primary" />
          <span class="metadata-title">生成信息</span>
        </div>
        <div class="metadata-grid">
          <div class="metadata-item">
            <span class="metadata-label">提供商</span>
            <span class="metadata-value">{{ result.provider }}</span>
          </div>
          <div class="metadata-item">
            <span class="metadata-label">模型</span>
            <span class="metadata-value">{{ result.model }}</span>
          </div>
          <div class="metadata-item">
            <span class="metadata-label">宽高比</span>
            <span class="metadata-value">{{ result.metadata?.aspect_ratio }}</span>
          </div>
          <div class="metadata-item">
            <span class="metadata-label">格式</span>
            <span class="metadata-value">{{ result.metadata?.response_format }}</span>
          </div>
          <div class="metadata-item">
            <span class="metadata-label">提示词长度</span>
            <span class="metadata-value">{{ result.usage?.prompt_length }} 字符</span>
          </div>
          <div class="metadata-item">
            <span class="metadata-label">生成数量</span>
            <span class="metadata-value">{{ result.usage?.images_generated }} 张</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import {
  PhArrowCounterClockwise,
  PhSparkle,
  PhWarning,
  PhDownload,
  PhCopy,
  PhImage,
  PhImages,
  PhPencil,
  PhGear,
  PhRectangle,
  PhFileImage,
  PhCaretDown,
  PhInfo,
  PhMagicWand,
  PhMagnifyingGlass,
  PhX,
  PhTag,
  PhToggleLeft,
  PhToggleRight,
} from '@phosphor-icons/vue'

/**
 * 表单数据
 */
const prompt = ref('')
const aspectRatio = ref('1:1')
const responseFormat = ref('url')

/**
 * 快捷提示词模板
 */
interface PromptTemplate {
  id: string
  name: string
  category: string
  prompt: string
  tags: string[]
}

const promptTemplates: PromptTemplate[] = [
  // 人物肖像类
  {
    id: 'portrait-1',
    name: '专业肖像',
    category: '人物肖像',
    prompt: '专业商务肖像照，正装，干净的背景，柔和的灯光，高清摄影，85mm镜头',
    tags: ['人物', '肖像', '商务', '专业'],
  },
  {
    id: 'portrait-2',
    name: '艺术肖像',
    category: '人物肖像',
    prompt: '艺术肖像摄影，戏剧性灯光，深色背景，情感表达，黑白摄影风格',
    tags: ['人物', '肖像', '艺术', '黑白'],
  },
  {
    id: 'portrait-3',
    name: '时尚肖像',
    category: '人物肖像',
    prompt: '时尚杂志风格肖像，彩妆精致，时尚服装，工作室灯光，高端摄影',
    tags: ['人物', '时尚', '杂志', '彩妆'],
  },

  // 自然风景类
  {
    id: 'landscape-1',
    name: '山景日出',
    category: '自然风景',
    prompt: '壮丽的山脉日出景象，金色阳光，云海缭绕，超广角镜头，风景摄影',
    tags: ['风景', '山脉', '日出', '自然'],
  },
  {
    id: 'landscape-2',
    name: '海滨夕阳',
    category: '自然风景',
    prompt: '美丽的海滨夕阳，波浪轻抚沙滩，橙红色天空，宁静祥和，长曝光效果',
    tags: ['风景', '海滨', '夕阳', '海浪'],
  },
  {
    id: 'landscape-3',
    name: '森林秘境',
    category: '自然风景',
    prompt: '神秘的森林深处，阳光透过树叶，薄雾弥漫，绿意盎然，童话般的氛围',
    tags: ['风景', '森林', '神秘', '阳光'],
  },

  // 动物宠物类
  {
    id: 'animal-1',
    name: '可爱小猫',
    category: '动物宠物',
    prompt: '一只可爱的小猫咪，毛茸茸的，大眼睛，坐在阳光下，温馨可爱，宠物摄影',
    tags: ['动物', '猫咪', '可爱', '宠物'],
  },
  {
    id: 'animal-2',
    name: '忠诚狗狗',
    category: '动物宠物',
    prompt: '忠诚的金毛犬，友善的表情，户外草地，阳光明媚，动物肖像摄影',
    tags: ['动物', '狗狗', '金毛', '户外'],
  },
  {
    id: 'animal-3',
    name: '野生动物',
    category: '动物宠物',
    prompt: '野生老虎在自然栖息地，威严雄壮，丛林背景，野生动物摄影，国家地理风格',
    tags: ['动物', '野生', '老虎', '自然'],
  },

  // 建筑空间类
  {
    id: 'architecture-1',
    name: '现代建筑',
    category: '建筑空间',
    prompt: '现代摩天大楼，玻璃幕墙，几何线条，蓝天白云，建筑摄影，对称构图',
    tags: ['建筑', '现代', '摩天楼', '几何'],
  },
  {
    id: 'architecture-2',
    name: '古典建筑',
    category: '建筑空间',
    prompt: '古典欧式建筑，石雕装饰，历史感，温暖的灯光，建筑细节，文艺复兴风格',
    tags: ['建筑', '古典', '欧式', '历史'],
  },
  {
    id: 'architecture-3',
    name: '室内设计',
    category: '建筑空间',
    prompt: '现代简约室内设计，明亮宽敞，极简家具，自然光线，室内摄影',
    tags: ['室内', '设计', '简约', '现代'],
  },

  // 艺术创意类
  {
    id: 'art-1',
    name: '抽象艺术',
    category: '艺术创意',
    prompt: '抽象艺术作品，色彩斑斓，流动的形状，现代艺术风格，创意表达',
    tags: ['艺术', '抽象', '色彩', '创意'],
  },
  {
    id: 'art-2',
    name: '科幻未来',
    category: '艺术创意',
    prompt: '未来科幻城市，霓虹灯光，飞行器，高科技建筑，赛博朋克风格',
    tags: ['科幻', '未来', '赛博朋克', '科技'],
  },
  {
    id: 'art-3',
    name: '梦幻奇境',
    category: '艺术创意',
    prompt: '梦幻般的奇幻世界，漂浮的岛屿，彩虹桥梁，魔法光芒，童话风格',
    tags: ['奇幻', '梦幻', '魔法', '童话'],
  },
]

/**
 * 模板相关状态
 */
const showTemplates = ref(false)
const selectedCategory = ref('全部')
const searchKeyword = ref('')

/**
 * 获取所有分类
 */
const categories = computed(() => {
  const cats = ['全部', ...new Set(promptTemplates.map((t) => t.category))]
  return cats
})

/**
 * 过滤后的模板
 */
const filteredTemplates = computed(() => {
  let filtered = promptTemplates

  // 按分类过滤
  if (selectedCategory.value !== '全部') {
    filtered = filtered.filter((t) => t.category === selectedCategory.value)
  }

  // 按关键词搜索
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(
      (t) =>
        t.name.toLowerCase().includes(keyword) ||
        t.prompt.toLowerCase().includes(keyword) ||
        t.tags.some((tag) => tag.toLowerCase().includes(keyword)),
    )
  }

  return filtered
})

/**
 * 响应数据接口
 */
interface ImageGenerationResult {
  provider: string
  model: string
  images: Array<{ url: string; index: number }>
  cost?: number
  usage?: {
    prompt_length: number
    images_generated: number
  }
  metadata?: {
    aspect_ratio: string
    response_format: string
  }
}

/**
 * 生成状态
 */
const generating = ref(false)
const error = ref('')
const generatedImages = ref<Array<{ url: string; index: number }>>([])
const result = ref<ImageGenerationResult | null>(null)
const debugMode = ref<boolean | null>(null)

/**
 * 重置表单
 */
const resetForm = () => {
  prompt.value = ''
  aspectRatio.value = '1:1'
  responseFormat.value = 'url'
  error.value = ''
  generatedImages.value = []
  result.value = null
}

/**
 * 选择模板
 */
const selectTemplate = (template: PromptTemplate) => {
  prompt.value = template.prompt
  showTemplates.value = false
}

/**
 * 切换模板面板显示
 */
const toggleTemplates = () => {
  showTemplates.value = !showTemplates.value
  if (showTemplates.value) {
    selectedCategory.value = '全部'
    searchKeyword.value = ''
  }
}

/**
 * 获取调试状态
 */
const fetchDebugStatus = async () => {
  try {
    const response = await fetch('http://localhost:8001/api/v1/ai/debug-status')
    if (response.ok) {
      const data = await response.json()
      debugMode.value = data.minimax_debug_mode
    }
  } catch (err) {
    console.warn('无法获取调试状态:', err)
  }
}

/**
 * 切换调试模式
 */
const toggleDebugMode = async () => {
  try {
    const response = await fetch('http://localhost:8001/api/v1/ai/toggle-debug-mode', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    })

    if (response.ok) {
      const data = await response.json()
      debugMode.value = data.minimax_debug_mode

      // 显示切换成功提示
      const message = `✓ ${data.message}`
      alert(message)

      console.log('🔄 调试模式切换成功:', data)
    } else {
      throw new Error('切换失败')
    }
  } catch (err) {
    console.error('❌ 切换调试模式失败:', err)
    alert('✗ 切换调试模式失败，请稍后重试')
  }
}

/**
 * 生成图片
 */
const generateImage = async () => {
  if (!prompt.value.trim()) {
    error.value = '请输入提示词'
    return
  }

  generating.value = true
  error.value = ''
  generatedImages.value = []
  result.value = null

  try {
    // 调用后端 API
    const response = await fetch('http://localhost:8001/api/v1/ai/text-to-image', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: JSON.stringify({
        prompt: prompt.value,
        aspect_ratio: aspectRatio.value,
        response_format: responseFormat.value,
      }),
    })

    if (!response.ok) {
      let errorMessage = '生成失败'
      try {
        const errorData = await response.json()
        errorMessage =
          errorData.detail || errorData.message || `HTTP ${response.status}: ${response.statusText}`
      } catch {
        errorMessage = `HTTP ${response.status}: ${response.statusText}`
      }
      throw new Error(errorMessage)
    }

    const data = await response.json()
    result.value = data

    // 验证响应数据结构
    if (!data.success) {
      throw new Error(data.message || '服务器返回失败状态')
    }

    if (!data.images || !Array.isArray(data.images) || data.images.length === 0) {
      throw new Error('服务器未返回有效的图片数据')
    }

    // 处理生成的图片
    generatedImages.value = data.images.map((img: { url: string; index: number }) => ({
      url: img.url,
      index: img.index,
    }))

    console.log('✅ 图片生成成功:', data)
  } catch (err: unknown) {
    const errorMessage = err instanceof Error ? err.message : String(err)
    error.value = errorMessage || '生成图片时发生未知错误'
    console.error('❌ 图片生成失败:', err)

    // 如果是网络错误，提供更友好的提示
    if (errorMessage.includes('Failed to fetch') || errorMessage.includes('ERR_FAILED')) {
      error.value = '无法连接到服务器，请检查后端服务是否正常运行'
    } else if (errorMessage.includes('CORS')) {
      error.value = '跨域请求被阻止，请检查服务器CORS配置'
    }
  } finally {
    generating.value = false
  }
}

/**
 * 下载图片
 */
const downloadImage = (url: string, index: number) => {
  const link = document.createElement('a')
  link.href = url
  link.download = `ai-generated-${Date.now()}-${index}.jpg`
  link.target = '_blank'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

/**
 * 复制图片 URL
 */
const copyImageUrl = async (url: string) => {
  try {
    await navigator.clipboard.writeText(url)
    alert('✓ 图片链接已复制到剪贴板')
  } catch (err) {
    console.error('复制失败:', err)
    alert('✗ 复制失败，请手动复制')
  }
}

/**
 * 组件挂载
 */
onMounted(() => {
  // 获取调试状态
  fetchDebugStatus()
})
</script>

<style scoped lang="scss">
.text-to-image-panel {
  padding: 0;
  animation: fadeIn 0.6s ease-out;
  background: linear-gradient(135deg, rgba(99, 102, 241, 0.05) 0%, rgba(168, 85, 247, 0.05) 100%);
  border-radius: 24px;
  overflow: hidden;
}

// 面板标题样式
.panel-header {
  position: relative;
  padding: 32px 32px 24px;
  background: linear-gradient(135deg, rgba(99, 102, 241, 0.1) 0%, rgba(168, 85, 247, 0.1) 100%);
  border-bottom: 1px solid rgba(99, 102, 241, 0.1);
  overflow: hidden;

  .header-content {
    display: flex;
    align-items: center;
    gap: 16px;
    position: relative;
    z-index: 2;
  }

  .header-icon {
    .icon-bg {
      width: 64px;
      height: 64px;
      background: linear-gradient(135deg, rgba(99, 102, 241, 0.2) 0%, rgba(168, 85, 247, 0.2) 100%);
      border-radius: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      backdrop-filter: blur(10px);
      border: 1px solid rgba(99, 102, 241, 0.2);
      box-shadow: 0 8px 32px rgba(99, 102, 241, 0.1);
    }
  }

  .header-text {
    flex: 1;
  }

  .header-title {
    font-size: 28px;
    font-weight: 700;
    background: linear-gradient(135deg, #6366f1 0%, #a855f7 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    margin-bottom: 8px;
    line-height: 1.2;
  }

  .header-subtitle {
    color: rgba(var(--bc), 0.7);
    font-size: 16px;
    line-height: 1.5;
    margin: 0;
  }

  .header-decoration {
    position: absolute;
    top: -50%;
    right: -20%;
    width: 200px;
    height: 200px;
    background: radial-gradient(circle, rgba(99, 102, 241, 0.1) 0%, transparent 70%);
    border-radius: 50%;
    animation: float 6s ease-in-out infinite;
  }

  .debug-status {
    margin-top: 12px;
  }

  .debug-info {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
  }

  .debug-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    border: 1px solid;
    backdrop-filter: blur(10px);

    &.debug-mode {
      background: linear-gradient(
        135deg,
        rgba(251, 146, 60, 0.1) 0%,
        rgba(245, 101, 101, 0.1) 100%
      );
      border-color: rgba(251, 146, 60, 0.3);
      color: #f59e0b;
    }

    &.production-mode {
      background: linear-gradient(135deg, rgba(34, 197, 94, 0.1) 0%, rgba(59, 130, 246, 0.1) 100%);
      border-color: rgba(34, 197, 94, 0.3);
      color: #22c55e;
    }
  }

  .debug-toggle-btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    border: 1px solid rgba(99, 102, 241, 0.3);
    border-radius: 16px;
    background: rgba(99, 102, 241, 0.1);
    color: #6366f1;
    font-size: 11px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    backdrop-filter: blur(10px);

    &:hover {
      background: rgba(99, 102, 241, 0.2);
      border-color: rgba(99, 102, 241, 0.5);
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(99, 102, 241, 0.2);
    }

    &:active {
      transform: translateY(0);
    }
  }
}

// 输入区域样式
.input-section {
  padding: 24px 32px;

  .input-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }

  .input-label {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    font-size: 16px;
    color: rgba(var(--bc), 0.9);

    .label-text {
      background: linear-gradient(135deg, #6366f1 0%, #a855f7 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
  }

  .char-counter {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 14px;
    font-weight: 500;

    .counter-text {
      color: rgba(var(--bc), 0.8);
    }

    .counter-divider {
      color: rgba(var(--bc), 0.4);
    }

    .counter-max {
      color: rgba(var(--bc), 0.6);
    }
  }

  .textarea-wrapper {
    position: relative;
  }

  .prompt-textarea {
    width: 100%;
    min-height: 120px;
    padding: 20px;
    border: 2px solid rgba(99, 102, 241, 0.2);
    border-radius: 16px;
    background: rgba(var(--b1), 0.8);
    backdrop-filter: blur(10px);
    font-size: 15px;
    line-height: 1.6;
    color: rgba(var(--bc), 0.9);
    resize: vertical;
    transition: all 0.3s ease;

    &::placeholder {
      color: rgba(var(--bc), 0.5);
    }

    &:focus {
      outline: none;
      border-color: rgba(99, 102, 241, 0.5);
      box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
      transform: translateY(-2px);
    }
  }

  .textarea-glow {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(99, 102, 241, 0.1) 0%, rgba(168, 85, 247, 0.1) 100%);
    border-radius: 16px;
    opacity: 0;
    transition: opacity 0.3s ease;
    pointer-events: none;
    z-index: -1;
  }

  .prompt-textarea:focus + .textarea-glow {
    opacity: 1;
  }

  .template-actions {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }

  .template-toggle-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 16px;
    border: 2px solid rgba(99, 102, 241, 0.2);
    border-radius: 12px;
    background: rgba(var(--b1), 0.8);
    backdrop-filter: blur(10px);
    color: rgba(var(--bc), 0.8);
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      border-color: rgba(99, 102, 241, 0.4);
      color: rgba(var(--bc), 1);
      transform: translateY(-2px);
    }

    &.active {
      border-color: rgba(99, 102, 241, 0.6);
      background: linear-gradient(135deg, rgba(99, 102, 241, 0.1) 0%, rgba(168, 85, 247, 0.1) 100%);
      color: #6366f1;
    }

    .template-count {
      background: linear-gradient(135deg, #6366f1 0%, #a855f7 100%);
      color: white;
      font-size: 12px;
      font-weight: 600;
      padding: 2px 6px;
      border-radius: 6px;
      min-width: 20px;
      text-align: center;
    }
  }
}

// 模板面板样式
.templates-panel {
  margin: 0 32px 24px;
  background: rgba(var(--b1), 0.9);
  border: 1px solid rgba(99, 102, 241, 0.2);
  border-radius: 20px;
  backdrop-filter: blur(15px);
  overflow: hidden;
  animation: slideDown 0.4s ease-out;

  .templates-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    background: linear-gradient(135deg, rgba(99, 102, 241, 0.1) 0%, rgba(168, 85, 247, 0.1) 100%);
    border-bottom: 1px solid rgba(99, 102, 241, 0.1);
  }

  .templates-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 600;
    color: rgba(var(--bc), 0.9);
  }

  .close-btn {
    width: 32px;
    height: 32px;
    border: none;
    border-radius: 8px;
    background: rgba(var(--bc), 0.1);
    color: rgba(var(--bc), 0.6);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;

    &:hover {
      background: rgba(var(--bc), 0.2);
      color: rgba(var(--bc), 0.9);
    }
  }

  .templates-filters {
    padding: 20px 24px;
    border-bottom: 1px solid rgba(99, 102, 241, 0.1);
  }

  .search-box {
    position: relative;
    margin-bottom: 16px;

    .search-icon {
      position: absolute;
      left: 14px;
      top: 50%;
      transform: translateY(-50%);
      color: rgba(var(--bc), 0.5);
    }

    .search-input {
      width: 100%;
      padding: 12px 16px 12px 40px;
      border: 2px solid rgba(99, 102, 241, 0.2);
      border-radius: 12px;
      background: rgba(var(--b1), 0.8);
      backdrop-filter: blur(10px);
      font-size: 14px;
      color: rgba(var(--bc), 0.9);
      transition: all 0.3s ease;

      &::placeholder {
        color: rgba(var(--bc), 0.5);
      }

      &:focus {
        outline: none;
        border-color: rgba(99, 102, 241, 0.5);
        box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
      }
    }
  }

  .category-tabs {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .category-tab {
    padding: 8px 16px;
    border: 1px solid rgba(99, 102, 241, 0.2);
    border-radius: 20px;
    background: rgba(var(--b1), 0.6);
    color: rgba(var(--bc), 0.7);
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    white-space: nowrap;

    &:hover {
      border-color: rgba(99, 102, 241, 0.4);
      color: rgba(var(--bc), 0.9);
    }

    &.active {
      background: linear-gradient(135deg, #6366f1 0%, #a855f7 100%);
      border-color: transparent;
      color: white;
    }
  }

  .templates-grid {
    padding: 20px 24px;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 16px;
    max-height: 400px;
    overflow-y: auto;
  }

  .template-card {
    padding: 16px;
    background: rgba(var(--b1), 0.8);
    border: 1px solid rgba(99, 102, 241, 0.1);
    border-radius: 16px;
    cursor: pointer;
    transition: all 0.3s ease;
    backdrop-filter: blur(10px);

    &:hover {
      border-color: rgba(99, 102, 241, 0.3);
      transform: translateY(-4px);
      box-shadow: 0 8px 32px rgba(99, 102, 241, 0.15);
    }
  }

  .template-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
  }

  .template-name {
    font-weight: 600;
    color: rgba(var(--bc), 0.9);
    font-size: 15px;
  }

  .template-category {
    font-size: 12px;
    color: rgba(var(--bc), 0.6);
    background: rgba(99, 102, 241, 0.1);
    padding: 4px 8px;
    border-radius: 8px;
    white-space: nowrap;
  }

  .template-prompt {
    color: rgba(var(--bc), 0.7);
    font-size: 13px;
    line-height: 1.5;
    margin-bottom: 12px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .template-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
  }

  .template-tag {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 11px;
    color: rgba(var(--bc), 0.6);
    background: rgba(var(--bc), 0.1);
    padding: 3px 6px;
    border-radius: 6px;
  }

  .templates-empty {
    padding: 60px 24px;
    text-align: center;
    color: rgba(var(--bc), 0.6);

    .empty-icon {
      margin-bottom: 16px;
      opacity: 0.5;
    }

    .empty-title {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 8px;
    }

    .empty-subtitle {
      font-size: 14px;
      opacity: 0.8;
    }
  }
}

// 参数设置样式
.params-section {
  padding: 0 32px 24px;

  .params-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 20px;
    font-weight: 600;
    font-size: 16px;
    color: rgba(var(--bc), 0.9);

    .params-title {
      background: linear-gradient(135deg, #6366f1 0%, #a855f7 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
  }

  .params-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 20px;
  }

  .param-group {
    .param-label {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 12px;
      font-weight: 500;
      font-size: 14px;
      color: rgba(var(--bc), 0.8);
    }

    .select-wrapper {
      position: relative;
    }

    .param-select {
      width: 100%;
      padding: 14px 16px;
      padding-right: 40px;
      border: 2px solid rgba(99, 102, 241, 0.2);
      border-radius: 12px;
      background: rgba(var(--b1), 0.8);
      backdrop-filter: blur(10px);
      font-size: 14px;
      color: rgba(var(--bc), 0.9);
      cursor: pointer;
      transition: all 0.3s ease;
      appearance: none;

      &:focus {
        outline: none;
        border-color: rgba(99, 102, 241, 0.5);
        box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
      }

      &:hover {
        border-color: rgba(99, 102, 241, 0.3);
      }
    }

    .select-icon {
      position: absolute;
      right: 14px;
      top: 50%;
      transform: translateY(-50%);
      color: rgba(var(--bc), 0.5);
      pointer-events: none;
      transition: transform 0.3s ease;
    }

    .select-wrapper:hover .select-icon {
      transform: translateY(-50%) rotate(180deg);
    }
  }
}

// 操作按钮样式
.action-section {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 16px;
  padding: 0 32px 32px;

  .reset-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 20px;
    border: 2px solid rgba(var(--bc), 0.2);
    border-radius: 12px;
    background: transparent;
    color: rgba(var(--bc), 0.7);
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      border-color: rgba(var(--bc), 0.3);
      color: rgba(var(--bc), 0.9);
      transform: translateY(-2px);
    }
  }

  .generate-btn {
    position: relative;
    padding: 0;
    border: none;
    border-radius: 16px;
    background: linear-gradient(135deg, #6366f1 0%, #a855f7 100%);
    color: white;
    font-weight: 600;
    cursor: pointer;
    overflow: hidden;
    transition: all 0.3s ease;

    &:not(.disabled):hover {
      transform: translateY(-3px);
      box-shadow: 0 12px 40px rgba(99, 102, 241, 0.4);
    }

    &.generating {
      .btn-glow {
        animation: pulse 2s ease-in-out infinite;
      }
    }

    &.disabled {
      opacity: 0.6;
      cursor: not-allowed;
      transform: none;
    }

    .btn-content {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 16px 32px;
      position: relative;
      z-index: 2;
    }

    .btn-icon {
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .btn-text {
      font-size: 16px;
      white-space: nowrap;
    }

    .btn-glow {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(135deg, rgba(255, 255, 255, 0.2) 0%, transparent 100%);
      opacity: 0;
      transition: opacity 0.3s ease;
    }

    &:hover .btn-glow {
      opacity: 1;
    }
  }
}

// 加载动画
.loading-spinner {
  width: 18px;
  height: 18px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

// 错误提示样式
.error-alert {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 20px;
  margin: 0 32px 24px;
  background: linear-gradient(135deg, rgba(239, 68, 68, 0.1) 0%, rgba(220, 38, 38, 0.1) 100%);
  border: 1px solid rgba(239, 68, 68, 0.2);
  border-radius: 16px;
  backdrop-filter: blur(10px);

  .error-icon {
    color: #ef4444;
    flex-shrink: 0;
    margin-top: 2px;
  }

  .error-content {
    flex: 1;
  }

  .error-title {
    font-weight: 600;
    color: #ef4444;
    margin-bottom: 4px;
  }

  .error-message {
    color: rgba(var(--bc), 0.8);
    font-size: 14px;
    line-height: 1.5;
  }
}

// 结果区域样式
.result-section {
  padding: 32px;
  background: rgba(var(--b1), 0.5);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(99, 102, 241, 0.1);
  animation: slideUp 0.6s ease-out;

  .result-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
  }

  .result-title {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 20px;
    font-weight: 700;
    color: rgba(var(--bc), 0.9);
  }

  .result-count {
    padding: 6px 12px;
    background: linear-gradient(135deg, rgba(99, 102, 241, 0.1) 0%, rgba(168, 85, 247, 0.1) 100%);
    border: 1px solid rgba(99, 102, 241, 0.2);
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    color: rgba(var(--bc), 0.7);
  }

  .images-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
    gap: 24px;
    margin-bottom: 32px;
  }

  .image-card {
    background: rgba(var(--b1), 0.8);
    border: 1px solid rgba(99, 102, 241, 0.1);
    border-radius: 20px;
    overflow: hidden;
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;
    animation: scaleIn 0.6s ease-out;

    &:hover {
      transform: translateY(-8px);
      box-shadow: 0 20px 60px rgba(99, 102, 241, 0.15);
      border-color: rgba(99, 102, 241, 0.3);
    }
  }

  .image-container {
    position: relative;
    aspect-ratio: 16/9;
    overflow: hidden;
  }

  .generated-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.4s ease;
  }

  .image-card:hover .generated-image {
    transform: scale(1.05);
  }

  .image-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(0, 0, 0, 0.1) 0%, rgba(0, 0, 0, 0.3) 100%);
    opacity: 0;
    transition: opacity 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .image-card:hover .image-overlay {
    opacity: 1;
  }

  .image-actions {
    display: flex;
    gap: 12px;
  }

  .action-btn {
    width: 44px;
    height: 44px;
    border: none;
    border-radius: 12px;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(10px);
    color: rgba(0, 0, 0, 0.7);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    transform: translateY(10px);

    &:hover {
      background: white;
      color: rgba(0, 0, 0, 0.9);
      transform: translateY(0) scale(1.1);
    }
  }

  .image-card:hover .action-btn {
    transform: translateY(0);
  }

  .image-gradient {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 60px;
    background: linear-gradient(transparent, rgba(0, 0, 0, 0.3));
    pointer-events: none;
  }

  .image-info {
    padding: 16px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .image-index {
    font-weight: 600;
    color: rgba(var(--bc), 0.8);
    font-size: 14px;
  }

  .image-cost {
    font-size: 12px;
    color: rgba(var(--bc), 0.6);
    background: rgba(99, 102, 241, 0.1);
    padding: 4px 8px;
    border-radius: 8px;
  }
}

// 元数据样式
.metadata-section {
  background: rgba(var(--b1), 0.6);
  border: 1px solid rgba(99, 102, 241, 0.1);
  border-radius: 16px;
  padding: 24px;
  backdrop-filter: blur(10px);

  .metadata-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 20px;
    font-weight: 600;
    color: rgba(var(--bc), 0.9);

    .metadata-title {
      background: linear-gradient(135deg, #6366f1 0%, #a855f7 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
  }

  .metadata-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
  }

  .metadata-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    background: rgba(var(--b1), 0.5);
    border: 1px solid rgba(99, 102, 241, 0.1);
    border-radius: 12px;
    transition: all 0.3s ease;

    &:hover {
      border-color: rgba(99, 102, 241, 0.2);
      transform: translateY(-2px);
    }
  }

  .metadata-label {
    font-size: 13px;
    color: rgba(var(--bc), 0.6);
    font-weight: 500;
  }

  .metadata-value {
    font-size: 13px;
    color: rgba(var(--bc), 0.9);
    font-weight: 600;
  }
}

// 动画定义
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

@keyframes scaleIn {
  from {
    opacity: 0;
    transform: scale(0.95);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

@keyframes pulse {
  0%,
  100% {
    opacity: 0.5;
  }
  50% {
    opacity: 1;
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .text-to-image-panel {
    border-radius: 16px;
  }

  .panel-header {
    padding: 24px 20px 20px;

    .header-content {
      gap: 12px;
    }

    .header-icon .icon-bg {
      width: 48px;
      height: 48px;
      border-radius: 14px;
    }

    .header-title {
      font-size: 24px;
    }

    .header-subtitle {
      font-size: 14px;
    }
  }

  .input-section,
  .params-section,
  .action-section {
    padding-left: 20px;
    padding-right: 20px;
  }

  .params-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .action-section {
    flex-direction: column-reverse;
    gap: 12px;

    .generate-btn,
    .reset-btn {
      width: 100%;
      justify-content: center;
    }
  }

  .result-section {
    padding: 24px 20px;

    .images-grid {
      grid-template-columns: 1fr;
      gap: 20px;
    }

    .metadata-grid {
      grid-template-columns: 1fr;
      gap: 12px;
    }
  }

  .error-alert {
    margin-left: 20px;
    margin-right: 20px;
  }

  .templates-panel {
    margin: 0 20px 20px;
    border-radius: 16px;

    .templates-header {
      padding: 16px 20px;
    }

    .templates-filters {
      padding: 16px 20px;
    }

    .templates-grid {
      padding: 16px 20px;
      grid-template-columns: 1fr;
      gap: 12px;
      max-height: 300px;
    }

    .template-card {
      padding: 12px;
    }

    .category-tabs {
      gap: 6px;
    }

    .category-tab {
      padding: 6px 12px;
      font-size: 12px;
    }
  }

  .debug-info {
    gap: 8px;
  }

  .debug-toggle-btn {
    font-size: 10px;
    padding: 4px 8px;
    gap: 4px;
  }
}
</style>
